package org.openrbac.rbac.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author 梁富贵
 * @Date 2024/5/3
 **/
@Configuration
@EnableAsync
public class AsyncConfig {

    private static final Logger LOGGER = LoggerFactory.getLogger(AsyncConfig.class);

    @Bean(name = "taskExecutor")
    public ThreadPoolTaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor() {
            @Override
            public void initialize() {
                try {
                    super.initialize();
                } catch (Exception e) {
                    LOGGER.error("Failed to initialize ThreadPoolTaskExecutor", e);
                    // 适当处理异常，如抛出自定义异常等
                }
            }
        };

        // 设置线程池的基本参数
        executor.setCorePoolSize(10);
        executor.setMaxPoolSize(20);
        executor.setQueueCapacity(500);
        executor.setKeepAliveSeconds(60);
        executor.setThreadNamePrefix("do-something-");

        // 使用DiscardPolicy处理任务拒绝
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());

        // 初始化线程池
        executor.initialize();

        return executor;
    }
}